#include "notemgrform.h"
#include "ui_notemgrform.h"
#include "tables.h"

#include <QSqlQuery>
#include <QMessageBox>
#include <QDateTime>
#include <QMenu>
#include <QCloseEvent>

NoteMgrForm::NoteMgrForm(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::NoteMgrForm)
{
    ui->setupUi(this);
    ui->stackedWidget->setCurrentIndex(0);
    readNotes();
    connect(ui->lwTitles,SIGNAL(customContextMenuRequested(QPoint)),
            this,SLOT(titleListContextMenuRequested(QPoint)));
}

NoteMgrForm::~NoteMgrForm()
{
    delete ui;
}

void NoteMgrForm::closeEvent(QCloseEvent *event)
{
    if(ui->stackedWidget->currentIndex() == 1){
        QListWidgetItem* item = ui->lwTitles->currentItem();
        if(item->text() != ui->edtTitle->text()){
            item->setData(NDR_MODIFY_TAG,true);
            item->setText(ui->edtTitle->text());
        }
        if(ui->NoteTexts->document()->isModified()){
            item->setData(NDR_MODIFY_TAG,true);
            item->setData(NDR_CONTENT,ui->NoteTexts->document()->toHtml("utf-8"));
            item->setData(NDR_LAST_EDIT_TIEM,QDateTime::currentDateTime().toMSecsSinceEpoch());
        }
    }
    bool isChanged = false;
    for(int i = 0; i < ui->lwTitles->count(); ++i){
        isChanged = ui->lwTitles->item(i)->data(NDR_MODIFY_TAG).toBool();
        if(isChanged)
            break;
    }
    if(isChanged || !delNoteIds.isEmpty()){
        if(QMessageBox::Yes == QMessageBox::warning(this,"",tr("存在有未保存的笔记，如果需要保存按确定，再返回到笔记列表保存笔记！"),
                                                    QMessageBox::Yes|QMessageBox::No,QMessageBox::Yes))
            event->ignore();
        else
            event->accept();
    }
    else
        event->accept();
}


void NoteMgrForm::titleListContextMenuRequested(const QPoint &pos)
{
    QListWidgetItem* item = ui->lwTitles->itemAt(pos);
    QMenu* menu = new QMenu(this);
    menu->addAction(ui->actAddNote);
    if(item){
        menu->addAction(ui->actDelNote);
    }
    menu->popup(mapToGlobal(pos));
}

/**
 * @brief 笔记内容被改变
 */
void NoteMgrForm::noteContentChanged()
{
    ui->btnSave->setEnabled(true);
}

/**
 * @brief 返回到笔记列表界面
 */
void NoteMgrForm::on_btnReturn_clicked()
{
    bool isNote = ui->stackedWidget->currentIndex() == 1;
    if(isNote){
        recordNoteContent();
        //if(item->data(NDR_MODIFY_TAG).toBool())
        //    ui->btnSave->setEnabled(true);
        ui->stackedWidget->setCurrentIndex(0);
        ui->btnReturn->setEnabled(false);
        ui->edtTitle->clear();
        ui->edtCrtTime->clear();
        ui->edtLastTime->clear();
    }
}

/**
 * @brief 双击笔记名，则打开笔记以编辑
 * @param item
 */
void NoteMgrForm::on_lwTitles_itemDoubleClicked(QListWidgetItem *item)
{
    disconnect(ui->edtTitle,SIGNAL(textEdited(QString)),this,SLOT(noteContentChanged()));
    disconnect(ui->NoteTexts,SIGNAL(textChanged()),this,SLOT(noteContentChanged()));
    ui->stackedWidget->setCurrentIndex(1);
    ui->NoteTexts->document()->setHtml(item->data(NDR_CONTENT).toString());
    ui->NoteTexts->document()->setModified(false);
    ui->btnReturn->setEnabled(true);
    ui->edtTitle->setText(item->text());
    QString ds = QDateTime::fromMSecsSinceEpoch(item->data(NDR_CREATE_TIME).toULongLong()).toString("yyyy-M-d h:m:s");
    ui->edtCrtTime->setText(tr("创建：%1").arg(ds));
    ds = QDateTime::fromMSecsSinceEpoch(item->data(NDR_LAST_EDIT_TIEM).toULongLong()).toString("yyyy-M-d h:m:s");
    ui->edtLastTime->setText(tr("修改：%1").arg(ds));
    connect(ui->NoteTexts,SIGNAL(textChanged()),this,SLOT(noteContentChanged()));
    connect(ui->edtTitle,SIGNAL(textEdited(QString)),this,SLOT(noteContentChanged()));
}

void NoteMgrForm::on_actAddNote_triggered()
{
    QListWidgetItem* item = new QListWidgetItem(tr("新笔记"),ui->lwTitles);
    item->setFlags(item->flags() | Qt::ItemIsEditable);
    item->setData(NDR_ID,0);
    item->setData(NDR_CREATE_TIME,QDateTime::currentDateTime().toMSecsSinceEpoch());
    item->setData(NDR_LAST_EDIT_TIEM,QDateTime::currentDateTime().toMSecsSinceEpoch());
    ui->lwTitles->editItem(item);
}

void NoteMgrForm::on_actDelNote_triggered()
{
    QListWidgetItem* item = ui->lwTitles->currentItem();
    if(item){
        int id = item->data(NDR_ID).toInt();
        if(id != 0)
            delNoteIds<<id;
        delete ui->lwTitles->takeItem(ui->lwTitles->currentRow());
        ui->btnSave->setEnabled(true);
    }
}

bool NoteMgrForm::initTable()
{
    QSqlQuery q;
    QString s = QString("select * from sqlite_master where name='%1'").arg(tbl_Notes);
    if(!q.exec(s))
        return false;
    if(!q.first()){
        s = QString("CREATE TABLE %1(id INTEGER PRIMARY KEY, %2 TEXT, %3 INTEGER, %4 INTEGER, %5 BLOB)")
                .arg(tbl_Notes).arg(fld_notes_title).arg(fld_notes_createTime)
                .arg(fld_notes_lastEditTime).arg(fld_notes_content);
        if(!q.exec(s))
            return false;
    }
    return true;
}

void NoteMgrForm::readNotes()
{
    if(!initTable()){
        QMessageBox::critical(this,"",tr("创建表失败？"));
        return;
    }
    QSqlQuery q;
    QString s = QString("select * from %1 order by %2 DESC").arg(tbl_Notes).arg(fld_notes_lastEditTime);
    if(!q.exec(s)){
        QMessageBox::critical(this,"",tr("读取笔记失败！"));
        return;
    }
    while(q.next()){
        int id = q.value(0).toInt();
        QString title = q.value(FI_NOTE_TITLE).toString();
        QString content = q.value(FI_NOTE_CONTENT).toString();
        qint64 crtTime = q.value(FI_NOTE_CREATETIME).toULongLong();
        qint64  lastEditTime = q.value(FI_NOTE_LASTTIME).toULongLong();
        QListWidgetItem* item = new QListWidgetItem(title,ui->lwTitles);
        item->setData(NDR_ID,id);
        item->setData(NDR_CONTENT,content);
        item->setData(NDR_CREATE_TIME,crtTime);
        item->setData(NDR_LAST_EDIT_TIEM,lastEditTime);
    }
}

bool NoteMgrForm::saveNotes()
{
    for(int i = 0; i < ui->lwTitles->count(); ++i){
        QListWidgetItem* item = ui->lwTitles->item(i);
        if(!item->data(NDR_MODIFY_TAG).toBool())
            continue;
        int id = item->data(NDR_ID).toInt();
        QString title = item->text();
        QString content = item->data(NDR_CONTENT).toString();
        qint64 crtTime = item->data(NDR_CREATE_TIME).toULongLong();
        qint64 lastTime = item->data(NDR_LAST_EDIT_TIEM).toULongLong();
        int noteId = id;
        if(!saveNote(noteId,title,content,lastTime,crtTime))
            return false;
        if(id == 0)
            item->setData(NDR_ID,noteId);
        item->setData(NDR_MODIFY_TAG,false);
    }
    if(!delNoteIds.isEmpty()){
        foreach(int id, delNoteIds){
            if(!removeNote(id))
                return false;
        }
        delNoteIds.clear();
    }
    return true;
}

bool NoteMgrForm::saveNote(int &id, QString title, QString content, qint64 lastTime, qint64 crtTime)
{
    QSqlQuery q;
    QString s;
    if(id == 0)
        s = QString("insert into %1(%2,%3,%4,%5) values(:title,:content,:crtTime,:lastTime)")
                .arg(tbl_Notes).arg(fld_notes_title).arg(fld_notes_content)
                .arg(fld_notes_createTime).arg(fld_notes_lastEditTime);
    else
        s = QString("update %1 set %2=:title,%3=:content,%4=:crtTime,%5=:lastTime where id=%6")
                .arg(tbl_Notes).arg(fld_notes_title).arg(fld_notes_content)
                .arg(fld_notes_createTime).arg(fld_notes_lastEditTime).arg(id);
    if(!q.prepare(s))
        return false;
    q.bindValue(":title",title);
    q.bindValue(":content",content);
    q.bindValue(":crtTime",crtTime);
    q.bindValue(":lastTime",lastTime);
    if(!q.exec())
        return false;
    if(id == 0){
        q.exec("select last_insert_rowid()");
        q.first();
        id = q.value(0).toInt();
    }
    return true;
}

bool NoteMgrForm::removeNote(int id)
{
    QSqlQuery q;
    QString s = QString("delete from %1 where id=%2").arg(tbl_Notes).arg(id);
    if(!q.exec(s))
        return false;
    return true;
}

/**
 * @brief 将当前显示的笔记内容记录到笔记的列表项内部
 */
void NoteMgrForm::recordNoteContent()
{
    QListWidgetItem* item = ui->lwTitles->currentItem();
    if(ui->edtTitle->text() != item->text()){
        item->setData(NDR_MODIFY_TAG,true);
        item->setText(ui->edtTitle->text());
    }
    QTextDocument* doc = ui->NoteTexts->document();
    if(doc->isModified()){
        item->setData(NDR_CONTENT,doc->toHtml("utf-8"));
        item->setData(NDR_MODIFY_TAG,true);
        item->setData(NDR_LAST_EDIT_TIEM,QDateTime::currentDateTime().toMSecsSinceEpoch());
        doc->setModified(false);
    }
}

void NoteMgrForm::on_btnSave_clicked()
{
    bool isNote = ui->stackedWidget->currentIndex() == 1;
    if(isNote)
        recordNoteContent();
    if(!saveNotes())
        QMessageBox::warning(this,"",tr("保存笔记失败"));
    else
        ui->btnSave->setEnabled(false);
}

